import React, { PureComponent } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Card, Popconfirm, Switch, message, Row, Col, Drawer, Button, Form, Input, Badge, Modal, Table, Descriptions } from 'antd';
import { BaseForm, PromotionChannelsForm } from '@/components/FormTools';
import { getAllCity, getCityByPage } from '@/services/auth';
import { decryptBugById, updateBugState, updateBugRemark } from '@/services/statistics';
import { secMap } from '@/configs/api.map';
import { StandardTable, SearchForm } from '@joy/joy-pro';
import { getValue, to } from '@/utils/smallTool';
import { connect } from 'dva';
import moment from 'moment';
import authUtil from '@/utils/auth';
import styles from './index.less';
import TextArea from 'antd/lib/input/TextArea';
import Note from './Note';

const pageInfo = { showSizeChanger: true, showQuickJumper: true, defaultPageSize: 10 };
const bugStatusConfig = {
  '0': '未完成',
  '1': '已完成',
  '2': '有疑问'
}
const bundTypeConfig = {
  '1': '绑定',
  '2': '刷新',
  '3': '激活',
  '4': '修改密码',
  '5': '解绑'
}
const exeCuteType = [{ value: '0', name: '绑定' }, { value: '1', name: '刷新' }, { value: '2', name: '激活' }, { value: '3', name: '修改密码' }
  , { value: '4', name: '解绑' }];

const drawerWidth = '70%';
const formProp = {
  labelCol: { span: 6 },
  wrapperCol: { span: 18 },
};
@connect(({ global, loading, bug, authority }) => ({
  tableData: bug.tableData,
  searchForm: bug.searchForm,
  tableLoading: loading.effects['bug/getDayBugByPage'],
  watermarkConfig: global.watermarkConfig,
}))
class Bug extends PureComponent {
  state = {
    activeRecord: false,
    params: {},
    pageRequest: {
      pageNum: 1,
      pageSize: 10,
    },
    drawerStatus: {
      decrypt: false,
      note: false
    },
    decryptData: {},
    loading: true,
    note: '',
    inputConfig: [
      {
        type: 'input',
        placeholder: '请输入用户ID',
        name: 'userId',
        label: '用户ID',
      },
      {
        type: 'select',
        placeholder: '请选择城市',
        name: 'cityCode',
        label: '城市',
        nameFiled: 'cityName',
        valueFiled: 'cityCode',
        optionData: [],
        selectProps: {
          showSearch: true,
          allowClear: true,
        }
      },
      {
        type: 'select',
        placeholder: '请选择绑卡类型',
        optionData: [{ value: '0', name: '社保卡' }, { value: '1', name: '公积金卡' }],
        name: 'gradType',
        label: '绑卡类型',
        selectProps: {
          allowClear: true,
        }
      },
      {
        type: 'select',
        placeholder: '请选择绑卡操作',
        optionData: exeCuteType,
        name: 'type',
        label: '绑卡操作',
        selectProps: {
          allowClear: true,
          search: true
        }
      },
      {
        type: 'select',
        placeholder: '请选择完成状态',
        optionData: [{ value: '0', name: '未完成' }, { value: '1', name: '已完成' }, { value: '2', name: '有疑问' }],
        name: 'state',
        label: '完成状态',
        selectProps: {
          allowClear: true,
        }
      },
      {
        type: 'datePicker',
        name: 'createDate',
        label: '日期',
        format: 'YYYY-MM-DD',
      }
    ],
  };
  constructor(props) {
    super(props);
    this.$drawerForm = React.createRef();
    const { pageRequest, params } = this.state;
    this.getSelectList().then(res => {
      this.getQueryList(params, pageRequest);
    })
  }

  // 条件筛选
  /**
   * @description 条件筛选 [搜索]
   * @author zhe
   * @date 2020-04-13
   * @param {*} formData
   * @param {*} reaclData
   * @param {*} isClear
   * @memberof
   */
  actionSearch = (formData, reaclData, isClear) => {
    const params = formData;
    if (formData.insuranceTime && formData.insuranceTime.length !== 0) {
      params.jobDateStart = params.insuranceTime[0];
      params.jobDateEnd = params.insuranceTime[1];
      delete params.insuranceTime;
    }
    const pageRequest = { pageNum: 1, pageSize: 10 };
    this.setState({
      params: params,
    });
    this.getQueryList(params, pageRequest);
  };

  /**
   * @description 请求列表数据
   * @author zhe
   * @date 2020-04-13
   * @param {*} params
   * @param {*} pageRequest
   * @memberof
   */
  getQueryList = (params, pageRequest) => {
    const type = 'bug/getDayBugByPage';
    const param = Object.assign(pageRequest, params);
    const { dispatch } = this.props;
    dispatch({
      type,
      payload: param,
    });
  };
  /**
   * @description 请求事件类型下拉列表数据
   * @author zhe
   * @date 2020-04-14
   * @memberof
   */
  getSelectList = async () => {
    const { inputConfig } = this.state;
    const dataObj = await getAllCity();
    if (dataObj && dataObj.code === '000000') {
      if (dataObj.data !== null) {
        inputConfig[1].optionData = dataObj.data;
        this.setState({ inputConfig: inputConfig });
        return Promise.resolve(dataObj.data);
      }
    }
    return Promise.reject();
  };
  // 刷新列表
  refreshList() {
    const pageRequest = { pageNum: 1, pageSize: 10 };
    this.setState({
      params: {},
    });
    this.getQueryList(this.state.params, pageRequest);
  };
  /**
   * @description 抽屉表单提交事件
   */
  onDrawerOk = async () => {
    const { drawerStatus } = this.state;
    const { getFieldsValue, validateFields } = this.$drawerForm.current.props.form;
    let validateError = null;
    let validateRes = null;
    [validateError, validateRes] = await to(validateFields());
    let postRes = await this.handleViewVisbile('note', { ...validateRes })
    if (postRes) this.changeDrawerStatus(false, 'note');
    return true;
  };
  async updateBugState(data) {
    let postRes = true;
    const dataObj = await updateBugState(data);
    if (dataObj && dataObj.code === '000000') {
      message.success('操作成功');
    } else {
      postRes = false;
      message.error('操作失败');
    }
    return postRes;
  };
  async getDecrypt(id) {
    const responseData = await decryptBugById(id);
    if (responseData && responseData.code == '000000') {
      this.setState({
        decryptData: responseData.data
      })
    }
    return false;
  }
  async updateBugRemark(data) {
    const responseData = await updateBugRemark(data);
    if (responseData && responseData.code == '000000') {
      message.success('保存成功')
      return true;
    }
    return false;
  };
  handleViewVisbile(type, data) {
    const config = {
      'note': 'updateBugRemark',   // 更新备注
      'decrypt': 'getDecrypt',    // 解密
      'update': 'updateBugState'  // 更新数据
    }
    return this[config[type]](data).then((res) => {
      res && this.refreshList();
      return res;
    })
  };
  /**
   * @description 切换抽屉状态
   * @author songs
   * @param {*} visible
   * @param {*} type
   * @param {*} title
   */
  changeDrawerStatus = (visible, type = '', activeRecord = {}) => {
    const { drawerStatus } = this.state;
    this.setState((oldState) => ({
      ...oldState,
      drawerStatus: {
        ...drawerStatus,
        [`${type}`]: visible
      },
      activeRecord
    }));
  };
  showDecryptView = (activeRecord = {}) => {
    const TYPE = 'decrypt';
    this.handleViewVisbile(TYPE, activeRecord.id);
    this.changeDrawerStatus(true, TYPE, activeRecord);
  };
  changeBugStatus = (record) => {
    this.handleViewVisbile('update', { state: record.state, id: record.id })
  };
  tableCol = () => {
    const OptionNode = ({ record }) => (
      <div className={styles.tableButtonGroup}>
        <Button
          type="link"
          style={{ marginRight: '20px' }}
          onClick={() => {
            this.showDecryptView(record);
          }}
        >
          解密
        </Button>
        <Button
          type="link"
          style={{ marginRight: '20px' }}
          onClick={() => {
            this.changeBugStatus(record);
          }}
        >
          已完成
        </Button>
        <Button
          type="link"
          style={{ marginRight: '20px' }}
          onClick={() => {
            this.changeDrawerStatus(true, 'note', record);
          }}
        >
          有疑问
        </Button>
      </div>
    );
    return [
      {
        title: '用户id',
        dataIndex: 'userId',
        width: '10%',
      },
      {
        title: '城市',
        dataIndex: 'cityName',
        width: '10%',
      },
      {
        title: '绑卡类型',
        dataIndex: 'gradType',
        width: '10%',
        render(text) {
          return text == 1 ? '公积金卡' : '社保卡'
        }
      },
      {
        title: '绑卡操作',
        dataIndex: 'busyType',
        width: '10%',
        render(text) { return bundTypeConfig[text] }
      },
      {
        title: '错误信息',
        dataIndex: 'errorMessage',
        width: '10%',
      },
      {
        title: '创建时间',
        dataIndex: 'createDate',
        width: '8%',
      },
      {
        title: '完成状态',
        dataIndex: 'state',
        width: '8%',
        render(text) { return bugStatusConfig[text] }
      },
      {
        title: '备注信息',
        dataIndex: 'remark',
        width: '8%',
      },
      {
        title: '操作',
        dataIndex: 'authSource2',
        width: '8%',
        render(text, record) {
          return <OptionNode record={record} />
        }
      },
    ];
  };

  render() {
    const { tableCol, onDrawerOk, changeDrawerStatus, handleSelectRows } = this;
    const { drawerStatus, selectedRows, inputConfig, decryptData, activeRecord } = this.state;
    const { tableLoading, watermarkConfig, tableData } = this.props;
    const { list = [], pagination = {} } = tableData;
    return (
      <div>
        <PageHeaderWrapper title="" className="hasContent">
          <div style={{ background: '#fff', padding: '20px 0px 0px 24px', marginBottom: '10px' }}>
            <SearchForm
              defaultInput={inputConfig.slice(0, 3)}
              moreInput={inputConfig.slice(3)}
              gutter={{ md: 10 }}
              useCol={{ sm: 24, md: 12, xl: 8, xxl: 8 }}
              onSearch={this.actionSearch}
            ></SearchForm>
          </div>
          <Card bordered={false}>
            <StandardTable
              isWatermark
              watermark={{ ...watermarkConfig }}
              dataSource={list}
              selectedRows={selectedRows}
              pagination={{ ...pagination, ...pageInfo }}
              columns={tableCol()}
              loading={tableLoading}
              rowKey={(record, index) => record.id}
              onChange={($pagination, filtersArg, sorter) => {
                this.handleStandardTableChange($pagination, this.state.params, sorter, 'bug/getDayBugByPage');
              }}
            ></StandardTable>
          </Card>
        </PageHeaderWrapper>
        <Modal
          title='解密'
          width={drawerWidth}
          destroyOnClose
          closable={false}
          onCancel={e => {
            changeDrawerStatus(false, 'decrypt');
          }}
          onOk={e => {
            changeDrawerStatus(false, 'decrypt');
          }}
          visible={drawerStatus['decrypt']}
        >
          <Row >
            <Col span={4} className={styles['text-align-justify']}>个人编号</Col>
            <Col span={20} className={[styles.blue, styles['special-marking']].join(' ')}>{decryptData.regNumber}</Col>
          </Row>
          <Row>
            <Col span={4} className={styles['text-align-justify']}>卡片编号</Col>
            <Col span={20} className={[styles.blue, styles['special-marking']].join(' ')}>{decryptData.account}</Col>
          </Row>
          <Row>
            <Col span={4} className={styles['text-align-justify']}>卡片登录密码</Col>
            <Col span={20} className={[styles.blue, styles['special-marking']].join(' ')}>{decryptData.password}</Col>
          </Row>
          <Row>
            <Col span={4} className={styles['text-align-justify']}>姓名</Col>
            <Col span={20} className={[styles.blue, styles['special-marking']].join(' ')}>{decryptData.name}</Col>
          </Row>
          <Row>
            <Col span={4} className={styles['text-align-justify']}>身份证号</Col>
            <Col span={20} className={[styles.blue, styles['special-marking']].join(' ')}>{decryptData.bodyCode}</Col>
          </Row>
          <Row>
            <Col span={4} className={styles['text-align-justify']}>手机号</Col>
            <Col span={20} className={[styles.blue, styles['special-marking']].join(' ')}>{decryptData.phoneNum}</Col>
          </Row>
        </Modal>
        <Modal
          title='备注信息'
          width={drawerWidth}
          destroyOnClose
          closable={false}
          onCancel={e => {
            changeDrawerStatus(false, 'note');
          }}
          onOk={onDrawerOk}
          visible={drawerStatus['note']}
        >
          <Note wrappedComponentRef={this.$drawerForm} note={activeRecord.note} id={activeRecord.id} />
        </Modal>
      </div>
    );
  }
}

export default Bug;
